/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: Frank
 * 系统版本: 1.0.0
 * 开发人员: Frank
 * 开发时间: 2020/3/5 23:38
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.sub;

import com.hazelcast.core.HazelcastInstance;
import com.spring.arch.datasource.client.DatasourceClient;
import com.spring.arch.datasource.dto.DatasourceMessage;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.jms.Message;
import com.spring.arch.common.jms.subscribe.MessageSubscriber;
import com.spring.arch.datasource.client.DatasourceClient;
import com.spring.arch.datasource.core.context.DatasourceParamConfig;
import com.spring.arch.datasource.core.helper.DBOperationHelper;
import com.spring.arch.datasource.dto.DatasourceMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Frank
 * @version 1.0.0.1
 * @since 2020/3/5 23:38
 */
@Slf4j
@Component
public class DatasourceMessageSubscriber extends MessageSubscriber {

    @Autowired
    private DBOperationHelper dbOperationHelper;
    @Resource
    private DatasourceClient datasourceClient;

    private static final String TOPIC_NAME = "DatasourceConfig";

    public DatasourceMessageSubscriber(@Autowired @Qualifier("hazelcastServerInstance") HazelcastInstance hazelcastInstance) {
        super(hazelcastInstance, TOPIC_NAME);
    }

    @Override
    protected void process(com.hazelcast.core.Message<Message> message) {
        Message msg = message.getMessageObject();
        if (msg instanceof DatasourceMessage) {
            DatasourceMessage datasourceMessage = (DatasourceMessage)msg;
            // 执行初始化
            dbOperationHelper.initializeDataSource(toParamConfig(datasourceMessage));
            // 回调更新数据源状态
            ResultDTO<Void> callRes = datasourceClient.initializeDataSource(datasourceMessage.getProjectId());
            if (callRes.isFailure()) {
                log.error("调用admin更新数据源初始化状态[{}]异常，响应信息[{}]", datasourceMessage.getProjectId(), callRes.getMessage());
            }
        }
    }

    private DatasourceParamConfig toParamConfig(DatasourceMessage configDTO) {
        return new DatasourceParamConfig(configDTO.getProjectId(),
                configDTO.getSchemaName(),
                configDTO.getUrl(),
                configDTO.getUsername(),
                configDTO.getPassword(), configDTO.getStatus());
    }
}
